import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/user_util.dart';
import 'package:star_author/widgets/empty_view/h_empty_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../model/shop_title_entity.dart';
import '../../../utils/number.dart';

class SortDialog extends StatefulWidget {
  final List<ShopTitleData> data;
  final Map sortMap;
  final bool isShowInputWidget;
  final bool isAddClassifyTitle;
  final bool isShowCheck;

  SortDialog({
    Key? key,
    this.data: const [],
    this.isShowInputWidget = true,
    this.isAddClassifyTitle = true,
    this.isShowCheck = false,
    required this.sortMap,
  }) : super(key: key);

  @override
  State<SortDialog> createState() => _SortDialogState();
}

class SortDialogHandler {
  //清楚筛选参数
  static void cleanValue(List<ShopTitleData> list, {Map? sortMap}) {
    list.forEach((element) {
      element.children?.forEach((element) {
        element.isSelect = false;
      });
    });

    if (sortMap != null) {
      sortMap.clear();
    }
  }
}

class _SortDialogState extends State<SortDialog> {
  double titleHeight = 40.w;

  List<ShopTitleData> data = [];

  TextEditingController minController = TextEditingController();
  TextEditingController maxController = TextEditingController();

  List checkList = [
    {'type': 'recording_video', 'isCheck': false, 'description': '只看有录播'},
  ];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      data = List.from(widget.data);

      if (UserUtil.isLogin(context)) {
        checkList.insert(
          0,
          {'type': 'without_tender', 'isCheck': false, 'description': '只看未出价'},
        );
      }

      checkList.forEach((element) {
        if (widget.sortMap['without_tender'] != null &&
            element['type'] == 'without_tender') {
          element['isCheck'] = widget.sortMap['without_tender'];
        }
        if (widget.sortMap['recording_video'] != null &&
            element['type'] == 'recording_video') {
          element['isCheck'] = widget.sortMap['recording_video'];
        }
      });

      setState(() {});

      //设置sort里面的为选择状态
      List list = widget.sortMap['list'] ?? [];
      data.forEach((element) {
        element.children?.forEach((element2) {
          int index_where =
              list.indexWhere((element3) => element3.id == element2.id);
          if (index_where != -1) {
            element2.isSelect = true;
          } else {
            element2.isSelect = false;
          }
        });
      });
    });

    LogUtil.v('object${widget.sortMap}');

    if (widget.sortMap['min'] != null && widget.sortMap['max'] != null) {
      minController.text = widget.sortMap['min'];
      maxController.text = widget.sortMap['max'];
    }

    if (mounted) setState(() {});
  }

  //重置
  reset() {
    maxController.clear();
    minController.clear();
    id = -1;
    checkList.forEach((element) {
      element['isCheck'] = false;
    });
    SortDialogHandler.cleanValue(data, sortMap: widget.sortMap);
    Get.back(result: {});
  }

  int id = -1;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        constraints: BoxConstraints(
          minHeight: Get.height * 0.4,
          maxHeight: Get.height * 0.8,
        ),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(16.w),
            topRight: Radius.circular(16.w),
          ),
        ),
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            Container(
              height: titleHeight,
              alignment: Alignment.centerLeft,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Padding(
                    padding: EdgeInsets.all(15),
                    child: SizedBox(
                      width: 14,
                      height: 14,
                    ),
                  ),
                  Center(
                    child: Text(
                      "筛选",
                      style: TextStyle(
                          fontSize: 16.sp,
                          color: Color(0xff333333),
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    child: Padding(
                      padding: EdgeInsets.all(15),
                      child: RoucesUtil.getAssetsIcon('ic_sort_close_lt', 14),
                    ),
                    onTap: () {
                      Get.back();
                    },
                  )
                ],
              ),
            ),
            Container(
              margin:
                  EdgeInsets.only(top: titleHeight, left: 12.w, right: 12.w),
              child: ListView(
                padding: EdgeInsets.zero,
                children: [
                  if (widget.isShowCheck) buildCheckList(),
                  if (widget.isShowInputWidget) ...[
                    buildText("价格区间"),
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                              child: Container(
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(50),
                              color: Color(0xFFF5F5F5),
                            ),
                            width: Get.width * 0.4,
                            child: TextField(
                              controller: minController,
                              textAlignVertical: TextAlignVertical.center,
                              inputFormatters: [
                                XNumberTextInputFormatter(isAllowDecimal: false)
                              ],
                              style: TextStyle(
                                fontSize: 14.sp,
                                color: Color(0xFF333333),
                              ),
                              textAlign: TextAlign.center,
                              keyboardType: TextInputType.number,
                              decoration: InputDecoration(
                                border: InputBorder.none,
                                isCollapsed: true,
                                contentPadding: EdgeInsets.zero,
                                hintText: '最小值',
                                hintStyle: TextStyle(
                                  fontSize: 14.sp,
                                  color: Color(0xFFCCCCCC),
                                ),
                              ),
                            ),
                            height: 40.w,
                            margin: EdgeInsets.only(right: 12.w),
                          )),
                          Text(
                            "—",
                            style: TextStyle(
                                fontSize: 14.sp,
                                color: Color(0xff333333),
                                fontWeight: FontWeight.w500),
                          ),
                          Expanded(
                              child: Container(
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(50),
                              color: Color(0xFFF5F5F5),
                            ),
                            width: Get.width * 0.4,
                            child: TextField(
                              controller: maxController,
                              inputFormatters: [
                                XNumberTextInputFormatter(isAllowDecimal: false)
                              ],
                              style: TextStyle(
                                fontSize: 14.sp,
                                color: Color(0xFF333333),
                              ),
                              textAlign: TextAlign.center,
                              keyboardType: TextInputType.number,
                              textAlignVertical: TextAlignVertical.center,
                              decoration: InputDecoration(
                                border: InputBorder.none,
                                isCollapsed: true,
                                contentPadding: EdgeInsets.zero,
                                hintText: '最大值',
                                hintStyle: TextStyle(
                                  fontSize: 14.sp,
                                  color: Color(0xFFCCCCCC),
                                ),
                              ),
                            ),
                            height: 40.w,
                            margin: EdgeInsets.only(left: 12.w),
                          )),
                        ],
                      ),
                    ),
                  ],
                  buildContent(),
                  Container(
                    height: 78.w,
                  ),
                ],
              ),
            ),
            Positioned(
              child: buildFooter(),
              bottom: 0,
              left: 0,
            ),
          ],
        ),
      ),
      onTap: () {
        FocusScope.of(context).unfocus();
      },
    );
  }

  buildContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: List.generate(
        data.length,
        (index) => Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            buildText("${data[index].name ?? ""}"),
            Container(
              child: Wrap(
                runSpacing: 10.w,
                spacing: 10.w,
                children: List.generate(
                  data[index].children?.length ?? 0,
                  (index2) => GestureDetector(
                    child: Container(
                      width: Get.width / 3.5,
                      height: 40.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color:
                              // id == data[index].children?[index2].id
                              (data[index].children?[index2].isSelect ?? false)
                                  ? Colors.white
                                  : Color(0xFFF5F5F5),
                          borderRadius: BorderRadius.circular(21.w),
                          border: Border.all(
                              width: 1,
                              color:
                                  // id == data[index].children?[index2].id
                                  (data[index].children?[index2].isSelect ??
                                          false)
                                      ? UIConstant.colorEBA07
                                      : Colors.transparent)),
                      child: Text(
                        '${data[index].children?[index2].name}',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color:
                              // id == data[index].children?[index2].id
                              (data[index].children?[index2].isSelect ?? false)
                                  ? UIConstant.colorEBA07
                                  : UIConstant.color33,
                        ),
                      ),
                    ),
                    onTap: () {
                      setState(() {
                        // id = (data[index].children![index2].id)!;
                        data[index].children?[index2].isSelect =
                            !(data[index].children?[index2].isSelect ?? false);
                      });
                    },
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  submit() {
    if (minController.text.isNotEmpty && maxController.text.isNotEmpty) {
      int min = int.parse(minController.text);
      int max = int.parse(maxController.text);
      if (min >= max) {
        CustomToast.show("最低价不能大于最高价");
        return;
      }
    }

    //已选中筛选项
    List ids = [];
    List<ShopTitleChildrenEntity> temps = [];
    data.forEach((e) {
      e.children?.forEach((element) {
        if (element.isSelect == true) {
          ShopTitleChildrenEntity entity =
              ShopTitleChildrenEntity.fromJson(element.toJson());
          if (widget.isAddClassifyTitle) {
            entity.name = (e.name ?? '') + '-' + (element.name ?? '');
          }
          temps.add(entity);
          ids.add(entity.id);
        }
      });
    });

    Map map = {
      "ids": ids,
      "list": temps,
    };
    if (minController.text.isNotEmpty && maxController.text.isNotEmpty) {
      map['min'] = minController.text;
      map['max'] = maxController.text;
    }

    Map result = {};
    if (ids.isEmpty &&
        minController.text.isEmpty &&
        maxController.text.isEmpty) {
      result = {};
    } else {
      result = map;
    }

    checkList.forEach((element) {
      bool isCheck = element['isCheck'];
      if (isCheck) {
        String type = element['type'];
        result[type] = isCheck;
      }
    });

    LogUtil.v("result:$result");

    if (mounted) setState(() {});
    Get.back(result: result);
  }

  buildFooter() {
    return Container(
      margin: EdgeInsets.only(
        bottom: 20.w,
        left: 12.w,
        right: 12.w,
      ),
      height: 42.w,
      width: Get.width - 24.w,
      child: Row(
        children: [
          Expanded(
            child: GestureDetector(
              child: Container(
                child: Text(
                  '重置',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: UIConstant.colorEBA07,
                  ),
                ),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(21.w),
                      bottomLeft: Radius.circular(21.w),
                    ),
                    border: Border.all(color: UIConstant.colorEBA07, width: 1)),
                alignment: Alignment.center,
              ),
              onTap: () {
                reset();
              },
            ),
          ),
          Expanded(
            child: GestureDetector(
              child: Container(
                alignment: Alignment.center,
                child: Text(
                  '确定',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.white,
                  ),
                ),
                decoration: BoxDecoration(
                  color: UIConstant.colorEBA07,
                  borderRadius: BorderRadius.only(
                    topRight: Radius.circular(21.w),
                    bottomRight: Radius.circular(21.w),
                  ),
                ),
              ),
              onTap: () {
                submit();
              },
            ),
          ),
        ],
      ),
    );
  }

  buildText(text) {
    return Container(
      child: Text(
        text,
        style: TextStyle(
            fontSize: 14.sp,
            color: Color(0xff333333),
            fontWeight: FontWeight.w500),
      ),
      margin: EdgeInsets.only(top: 12.w, bottom: 12.w),
    );
  }

  Widget buildCheckList() {
    return ListView.builder(
      itemBuilder: (ctx, index) {
        return buildCheckItem(index);
      },
      itemCount: checkList.length,
      shrinkWrap: true,
      padding: EdgeInsets.zero,
    );
  }

  Widget buildCheckItem(int index) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        checkList[index]['isCheck'] = !checkList[index]['isCheck'];
        setState(() {});
      },
      child: Container(
        margin: EdgeInsets.only(
            bottom: (index != checkList.length - 1) ? 20.w : 10.w),
        child: Row(
          children: [
            checkList[index]['isCheck']
                ? Image.asset(
                    "images/ic_expected_recieved_reason_lt.png",
                    width: 18.w,
                  )
                : Container(
                    width: 18.w,
                    height: 18.w,
                    decoration: BoxDecoration(
                      border: Border.all(color: UIConstant.color97, width: 1.w),
                      borderRadius: BorderRadius.all(
                        Radius.circular(100),
                      ),
                    ),
                  ),
            HEmptyView(10.w),
            Text(
              checkList[index]['description'],
              style: TextStyle(
                fontSize: 14.sp,
                color: UIConstant.color33,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
